<template>
  <div class="app-container">
    <el-card class="search_card" shadow="hover">
      <div>
        <i class="el-icon-search" />
        <span>筛选搜索</span>
        <el-button
          style="margin-left:20px;"
          type="primary"
          size="small"
          icon="el-icon-search"
          @click="handleSearchList"
        >
          搜索
        </el-button>
        <el-button
          icon="el-icon-refresh"
          size="small"
          @click="handleResetSearch"
        >
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form
          :inline="true"
          size="small"
          :model="queryParams"
          label-width="140px"
        >
          <el-form-item label="课程选择：">
            <el-select
              filterable
              v-model="queryParams.courseId"
              placeholder="请选择课程"
              @change="handleSearchList"
              clearable
            >
              <el-option
                v-for="item in courseOptions"
                :key="item.id"
                :label="item.courseName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型选择：">
            <el-select
              v-model="queryParams.topicType"
              placeholder="请选择题型"
              @change="handleSearchList"
              clearable
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.id"
                :label="item.type"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="operate-container" shadow="hover" style="margin: 20px 0px;">
      <i class="el-icon-tickets" />
      <span>题库列表</span>
      <el-button
        icon="el-icon-plus"
        size="mini"
        type="primary"
        @click="handleAddQuestion"
        class="ml20"
      >
        录入题目
      </el-button>
      <el-button
        icon="el-icon-delete"
        size="mini"
        type="danger"
        @click="delAllSelection"
        class="ml20"
      >
        批量删除
      </el-button>
    </el-card>
    <div class="table-container">
      <el-table
        ref="questionsList"
        :data="list"
        style="width: 100%;"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          align="center"
          width="50"
        ></el-table-column>
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="题目：">
                <span>{{ props.row.context }}</span>
              </el-form-item>
              <el-form-item label="选项：" v-if="props.row.topicType == 0">
                <div v-for="(item,index) in props.row.answerList" :key="index" class="imgBox">
                  <p class="nopadding" v-if="index == 0">A：</span>{{item.context}}</p>
                  <p class="nopadding" v-if="index == 1">B：</span>{{item.context}}</p>
                  <p class="nopadding" v-if="index == 2">C：</span>{{item.context}}</p>
                  <p class="nopadding" v-if="index == 3">D：</span>{{item.context}}</p>
                  <p class="nopadding" v-if="index == 4">E：</span>{{item.context}}</p>
                  <p class="nopadding" v-if="index == 5">F：</span>{{item.context}}</p>
                </div>
              </el-form-item>
              <el-form-item label="正确答案：">
                <span class="red">{{getAnswer(props.row.answerList)}}</span>
              </el-form-item>
              <el-form-item label="答案解析：">
                <span>{{props.row.analysis}}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column
          type="index"
          label="序号"
          align="center"
          width="50"
        ></el-table-column>
        <el-table-column label="分类" align="center" width="150">
          <template slot-scope="scope">
            {{ getCateName(scope.row.courseId) }}
          </template>
        </el-table-column>
        <el-table-column label="题型" align="center" width="100">
          <template slot-scope="scope">
            <el-tag type="primary" v-if="scope.row.topicType == 0"
              >选择题</el-tag
            >
            <el-tag type="warning" v-else>判断题</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="试题内容"
          align="center"
          prop="context"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="录入时间" align="center" width="155">
          <template slot-scope="scope">
            {{ formatT(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-edit"
              size="mini"
              type="primary"
              @click="handleUpdateInfo(scope.$index, scope.row)"
            >
              编辑
            </el-button>
            <el-button
              icon="el-icon-delete"
              size="mini"
              type="danger"
              @click="handleDel(scope.$index, scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="fetchQuestions"
    />

    <el-dialog :title="title" :visible.sync="dialogVisible" width="60%">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="课程选择：" prop="courseId">
              <el-select
                filterable
                v-model="form.courseId"
                placeholder="请选择课程"
                @change="changeCourse"
              >
                <el-option
                  v-for="item in courseOptions"
                  :key="item.id"
                  :label="item.courseName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
              <span style="margin-left: 10px;">该课程最少录入<span class="blue">{{choiceCount}}</span>道选择题，<span class="orange">{{judgeCount}}</span>道判断题</span>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="题型选择：" prop="topicType">
              <el-select
                v-model="form.topicType"
                placeholder="请选择题型"
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.id"
                  :label="item.type"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="题干：" prop="context">
              <el-input
                type="textarea"
                :autosize="{ minRows: 2 }"
                placeholder="请输入题干内容"
                v-model="form.context"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="选项：" prop="answer">
              <el-radio-group
                v-model="form.answer"
                v-if="form.topicType == 0"
                class="select_box"
                ref="select"
              >
                <div v-for="item in number" :key="item.index">
                  <el-radio :label="item.index" class="select">
                    <el-input
                      type="textarea"
                      :autosize="{ minRows: 2 }"
                      placeholder="请输入选项内容"
                      v-model="item.context"
                    >
                    </el-input>
                  </el-radio>
                </div>
              </el-radio-group>
              <el-button
                type="primary"
                size="small"
                icon="el-icon-circle-plus-outline"
                v-if="form.topicType == 0"
                @click="addSelect"
                >添加选项</el-button
              >
              <el-radio-group v-model="form.answer" v-if="form.topicType == 1">
                <el-radio :label="0">
                  <el-tag type="primary">正确</el-tag>
                </el-radio>
                <el-radio :label="1">
                  <el-tag type="danger">错误</el-tag>
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="20">
            <el-form-item label="解析：" prop="analysis">
              <el-input
                type="textarea"
                :autosize="{ minRows: 2 }"
                placeholder="请输入题目解析"
                v-model="form.analysis"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryCourseList,
  queryCourseListById,
  queryTopicList,
  addTopic,
  updateTopic,
  delTopic
} from "@/api/school/school";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

const defaultListQuery = {
  pageNum: 1,
  pageSize: 10,
  courseId: undefined,
  topicType: undefined
};

export default {
  name: "questionList",
  components: { Treeselect },
  data() {
    return {
      // 查询参数
      queryParams: Object.assign({}, defaultListQuery),
      courseOptions: [],
      typeOptions: [
        {
          id: '0',
          type: "选择题"
        },
        {
          id: '1',
          type: "判断题"
        }
      ],

      list: [],
      total: 0,

      // 多选框数据
      ids: [],

      title: "",
      dialogVisible: false,
      form: {
        answerList: []
      },
      rules: {
        courseId: [{ required: true, message: "请选择课程", trigger: "blur" }],
        topicType: [{ required: true, message: "请选择题型", trigger: "blur" }],
        context: [{ required: true, message: "题干不能为空", trigger: "blur" }],
        answer: [{ required: true, message: "答案不能为空", trigger: ["blur", "change"] }],
        analysis: [{ required: true, message: "解析不能为空", trigger: "blur" }]
      },
      number: [
        {
          index: 0,
          context: ""
        },
        {
          index: 1,
          context: ""
        }
      ],
      // 提示选择题数量、判断题数量
      choiceCount: 0,
      judgeCount: 0
    };
  },
  created() {
    this.fetchCourseList();
    this.fetchQuestions();
  },
  watch: {},
  methods: {
    // 获取指定课程的题库最低数量
    changeCourse(){
      queryCourseListById(this.form.courseId).then(res => {
        if(res.code == 200){
          this.choiceCount = res.data.choiceQuestion;
          this.judgeCount = res.data.judgeQuestion;
          console.log(res.data.choiceQuestion,'选择题数量')
          console.log(res.data.judgeQuestion,'判断题数量')
        }
      });
    },
    // 获取课程
    fetchCourseList() {
      queryCourseList({
        pageNum: 1,
        pageSize: 10000
      }).then(res => {
        this.courseOptions = res.rows;
        console.log(this.courseOptions,'课程----')
      });
    },
    // 获取题库题目
    fetchQuestions() {
      queryTopicList(this.queryParams).then(res => {
        if (res.code == 200) {
          console.log(res);
          this.list = res.rows;
          this.total = res.total;
        } else {
          return this.msgError("获取题库题目失败");
        }
      });
    },

    // 点击重置
    handleResetSearch() {
      this.queryParams = Object.assign({}, defaultListQuery);
      this.fetchQuestions();
    },
    // 点击搜索
    handleSearchList() {
      this.queryParams.pageNum = 1;
      this.fetchQuestions();
    },

    // 处理类名
    getCateName(id) {
      let cate = this.courseOptions.find(item => {
        return item.id == id;
      });
      if(cate == undefined){
        return null;
      }else{
        return cate.courseName;
      }
    },

    changeType(e) {
      console.log(e);
    },
    // 处理答案
    getAnswer(row){
      let answerIndex = row.findIndex(item => {
        return item.correct == 1
      })
      if(answerIndex == -1){
        return '未录入正确答案'
      }else{
        return row[answerIndex].context;
      }
    },

    addSelect() {
      let i = this.number.length;
      this.number.push({
        index: i,
        context: ""
      });
    },

    // 多选框选择
    handleSelectionChange(val) {
      this.ids = val.map(item => item.id);
    },
    // 点击批量删除按钮
    delAllSelection() {
      if (this.ids.length == 0) {
        return this.msgError("必须选择一项进行操作！");
      } else {
        var str = this.ids.join(",");
      }
      this.$confirm("确定要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteData(str);
          this.ids = [];
        })
        .catch(() => {});
    },
    // 点击删除按钮
    handleDel(index, row) {
      this.$confirm("确定要删除吗?", "提示", {
        type: "warning"
      })
        .then(() => {
          // console.log(row.id);
          this.deleteData(row.id);
        })
        .catch(() => {});
    },
    // 实现删除商品
    deleteData(id) {
      delTopic(id).then(res => {
        if (res.code == 200) {
          this.msgSuccess("删除成功");
          this.fetchQuestions();
        } else {
          this.msgError("删除失败！");
        }
      });
    },

    // 点击添加题目
    handleAddQuestion() {
      this.choiceCount = 0;
      this.judgeCount = 0;
      this.form = {
        answerList: []
      };
      this.number = [{index: 0,context: ''},{index: 1,context: ''}];
      this.title = "题目录入";
      this.dialogVisible = true;
      console.log(this.form)
    },
    // 点击编辑题目
    handleUpdateInfo(index, row) {
      this.form = row;
      this.number = [];
      this.dialogVisible = true;
      this.title = "题目修改"
      this.number = this.form.answerList;                           
      this.number.forEach((item,index)=>{
        item.index = index;
      })
      // console.log(this.number)
      let i = this.form.answerList.findIndex(item => {
        return item.correct == 1;
      })
      this.$set(this.form,"answer",i)
      this.$forceUpdate();
      // console.log(this.form.answer)
      this.changeCourse();
    },
    // 提交表单
    submitForm() {
      this.$refs["form"].validate(valid => {       
        console.log(this.form)
        if(this.form.topicType == '0'){
          var data = [];
          this.number.forEach((item,index) => {
            if(item.context !== ''){
              data.push(item)
            }
          })
          this.form.answerList = data;
          this.form.answerList.forEach(item => {
            item.correct = 0;
          })
          this.form.answerList[this.form.answer].correct = 1;
        }else{
          if(this.form.id !== undefined){
            this.form.answerList = this.number;
            this.form.answerList.forEach(item => {
              item.correct = 0;
            })
            this.form.answerList[this.form.answer].correct = 1;
          }else{
            this.form.answerList = [{correct: 0,context: '正确'},{correct: 0,context: '错误'}];
            this.form.answerList[this.form.answer].correct = 1;
          }
        }
        if (valid) {
          if (this.form.id !== undefined) {
            updateTopic(this.form).then(res => {
              if (res.code === 200) {
                this.msgSuccess("修改成功");
                this.dialogVisible = false;
                this.form = {
                  answerList: []
                };
                this.choiceCount = 0;
                this.judgeCount = 0;
                this.number = [{index: 0,context: ''},{index: 1,context: ''}];
                this.fetchQuestions();
              } else {
                this.msgError(res.msg);
              }
            });
          } else {
            addTopic(this.form).then(res => {
              if (res.code === 200) {
                this.msgSuccess("新增成功");
                this.dialogVisible = false;
                this.form = {
                  answerList: []
                };
                this.number = [{index: 0,context: ''},{index: 1,context: ''}];
                this.fetchQuestions();
                this.choiceCount = 0;
                this.judgeCount = 0;
              } else {
                this.msgError(res.msg);
              }
            });
          }
        }
      });
    },
    // 取消提交
    cancel() {
      this.form = {
        answerList: []
      };
      this.number = [{index: 0,context: ''},{index: 1,context: ''}];
      this.dialogVisible = false;
    }
  }
};
</script>
<style lang="scss" scoped>
.table-container {
  margin-top: -21px;
}
.ml20 {
  margin-left: 20px;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 100%;
}
.search_card {
  overflow: unset !important;
}
.select_box {
  display: block;
  vertical-align: middle;
}
.select {
  display: block;
  margin-bottom: 10px;
  vertical-align: middle;
}
.nopadding {
  padding: 0;
  margin: 0;
}
.red {
  color: red;
}
.blue {
  font-size: 17px;
  color: rgb(77, 122, 248);
}
.orange{
  font-size: 17px;
  color: rgb(247, 132, 91);
}
</style>
